package com.linzm.leetcode.primary.exercises3_20230122;

/**
 * @Author zimingl
 * @Date 2023/1/26 1:22
 * @Description: 交替合并字符串
 */
public class Demo33_1768 {
    /**
     * 给你两个字符串 word1 和 word2 。请你从 word1 开始，通过交替添加字母来合并字符串。
     * 如果一个字符串比另一个字符串长，就将多出来的字母追加到合并后字符串的末尾。
     * 返回 合并后的字符串 。
     * 输入：word1 = "ab", word2 = "pqrs"
     * 输出："apbqrs"
     * 解释：注意，word2 比 word1 长，"rs" 需要追加到合并后字符串的末尾。
     * word1：  a   b
     * word2：    p   q   r   s
     * 合并后：  a p b q   r   s
     */
    public static void main(String[] args) {
        Demo33_1768 demo33_1768 = new Demo33_1768();
        String word1 = "ab", word2 = "pqrs";
        String mergeAlternately = demo33_1768.mergeAlternately(word1, word2);
        System.out.println(mergeAlternately);
    }

    private String mergeAlternately(String word1, String word2) {
        String target = "";
        int len, n = 0;
        if (word1.length() > word2.length()) {
            len = word2.length();
        } else {
            len = word1.length();
            n++;
        }
        for (int i = 0; i < len; i++) {
            target = target + word1.charAt(i) + word2.charAt(i);
        }
        if (n == 0) {
            target += word1.substring(len);
        }
        if (n == 1) {
            target += word2.substring(len);
        }
        return target;
    }
}
